package idv.arthur.jenkins;

import idv.arthur.widgets.URLConnectionUtil;
import idv.arthur.widgets.Widgets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class UpdateJobPostBuild {

	public static void main(String[] args) throws Exception {
		final Widgets wid = new Widgets();
		final String jobName = "MR_BL_DevOps";
		final String urlStr =wid.JENKINSURL+"job/"+jobName+"/config.xml";
		final int chkInId = 9999;
		
		
		/**
		 * 同意提交
		 * 	簽入SVN
		 * 	1.	寫入SVN
		 * 
		 * 	(jenkins 需安裝plugin==>HTTP Request Plugin)
		 * 	開始執行Build版封裝
		 * 	1.	 修改目標job的  postBuild 執行 servlet，修改chkInId的值
		 * 	2.	
		 * 	
		 * */
		
		
		final String url = wid.APSERVER_HOST+"TriggerNext?jobName="+jobName+"&chkInId="+chkInId;
		
		Map<String,Object> map = new HashMap<String,Object>();
        InputStream ins = null ;
        // 連線取得資料
        ins = URLConnectionUtil.doGet(urlStr,true,wid.JENKINS_USR,wid.JENKINS_PWD,map);
		final SAXReader reader = new SAXReader();
		final Document document = reader.read(ins);
		ins.close();
		Element root = document.getRootElement();

		Iterator<Element> it = root.elementIterator();

		while (it.hasNext()) {
			Element e1 = it.next();
			if ( "postbuilders".equalsIgnoreCase(e1.getName() ) ){
				e1 = (Element) e1.elementIterator().next();	//jenkins.plugins.http__request.HttpRequest plugin="http_request@1.8.2"
				e1 = (Element) e1.elementIterator().next();	//url
				e1.setText(url);
				
				
				PostMethod postMethod = new PostMethod(urlStr);
				postMethod.setRequestHeader("Content-type","application/xml; charset=UTF-8");
				postMethod.setRequestBody(new FileInputStream( saveToFile(new File("tmp"+System.currentTimeMillis()+".xml"), document) ));
				
				HttpClient client = new HttpClient();
				client.getParams().setAuthenticationPreemptive(true);
				client.getState().setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(wid.JENKINS_USR,wid.JENKINS_PWD) );
				
				String res2 = client.executeMethod(postMethod)==200?"OK":"failure";
				System.out.println(res2);
			}
		}

	}
	
	private static File saveToFile(File storedFile,Document document) {
		if (storedFile.exists())
			storedFile.delete();

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		XMLWriter writer = null;
		try {
			storedFile.createNewFile();

			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			fos = new FileOutputStream(storedFile);
			osw = new OutputStreamWriter(fos, Charset.forName("utf-8"));
			writer = new XMLWriter(osw, format);
			writer.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) writer.close();
				if (osw != null) osw.close();
				if (fos != null) fos.close();
			} catch (IOException e) {
			}
		}
		return storedFile;
	}

}
